package your.pachet;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;





public class Prognoza extends ListActivity implements View.OnClickListener {
	 PersonajeAdapter adapter;
	 Button b;
	 ProgressDialog dialog;
	 int ok;
	 
	 
	 
	 private final static String NOTES="notes.txt";
	
	 
	 public void onActivityResult (int requestCode, int responseCode, Intent data)
	    {
	    	//dialog.cancel();
	    	if (requestCode == 100)
	    	{
	    		// s-a apasat butonul Adauga
	    		if (responseCode==RESULT_OK)
	    		{
	    			String nume = data.getStringExtra("nume");
	    				 
	    			adapter.adaugaOras(nume);
	    		}
	    		
	    		else if (responseCode==0)
	    		{
	    		}
	    	}
	    }
	 
	 
	 
	 public void onClick(View view) {
		
			
		
		 Intent i = new Intent(Prognoza.this, Oras.class);
		 
		 startActivityForResult (i, 100);
			
		} 
	 
	 
	 public void onPause() {
	    	super.onPause();
	    	try {
		    	OutputStreamWriter out = new OutputStreamWriter(openFileOutput(NOTES, 0));
		    	out.write(adapter.ialista());
		    	out.close();
	    	} catch (Throwable t) {
	    	Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
	    	}
	    }
 
	 
	 
	 
	 
	 
	    @Override
	    public void onCreate (Bundle savedInstanceBundle)
	    {
	    	super.onCreate (savedInstanceBundle);
	        adapter=new PersonajeAdapter(Prognoza.this);
	    
	    	
	    	try {
		    	InputStream in = openFileInput(NOTES);
		    	if (in != null) {
			    	InputStreamReader tmp = new InputStreamReader(in);
			    	BufferedReader reader = new BufferedReader(tmp);
			    	String str;
	 
			    
	 
			    	while ((str = reader.readLine()) != null) {
			    		adapter.adaugaOras(str);
			    	}
			    	in.close();
	 
			   
			    	
			    	
			    	
			    	
		    	}
	    	} catch (java.io.FileNotFoundException e) {
	    		// that's OK, we probably haven't created it yet
	    	} catch (Throwable t) {
	    
	    	}
	    	
	    	
	    	
	    	
	    	
	    	
	        setContentView (R.layout.main);
	        setListAdapter (adapter);
	        b=(Button)findViewById(R.id.button1);
	        b.setOnClickListener(this);
	        
	        
	        
	 
	       
	        getListView().setOnItemLongClickListener(new OnItemLongClickListener() 
			{
	 
				public boolean onItemLongClick(AdapterView<?> listAdapter, View view,
						int position, long id) 
				{
					adapter.stergeOras(position);
					
	                              
					return true;
				}
			});
	    }
	 
	    @Override
	    public void onListItemClick (ListView list, View v, final int position, long id)
	    {
	    dialog = ProgressDialog.show(Prognoza.this, "Loading", 
                "They see me rollin'                        They hatin'", true);
	   
	        
	        
	        
	        new Thread()
	        {
	        	public void run ()
	        	{
	        		String responseBody=null;
	        		
	        		String o = (String)adapter.getItem (position);
	        		HttpGet getMethod=new HttpGet("http://www.google.com/ig/api?weather="+o);
	        		 
	     	       
	        		
	    	        HttpClient client = new DefaultHttpClient ();
	    	    	
	    	 
	    	 
	    	    		ResponseHandler<String> responseHandler=new BasicResponseHandler();
	    	    		
	    	    	try{
							responseBody=client.execute(getMethod, responseHandler);
						} catch (ClientProtocolException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	    	    		 Document d=null;
	    	    	      Intent intent = new Intent(Prognoza.this, Meteo.class);
	    	    	      try {
	    	    	          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	    	    	          DocumentBuilder builder = factory.newDocumentBuilder();
	    	    	          InputSource is = new InputSource( new StringReader( responseBody ) );
	    	    	          d = builder.parse( is );
	    	    	   
	    	    	           
	    	    	     Node nod=d.getFirstChild();
	    	    	      nod=nod.getFirstChild();
	    	    	    NodeList nodl=nod.getChildNodes();
	    	    	    NodeList l=nodl.item(0).getChildNodes();
	    	    	    Element el=(Element) l.item(4);
	    	    	     
	    	    	
	    	    	      
	    	    	      
	    	    	      intent.putExtra("data1",el.getAttribute("data") );
	    	    	      
	    	    	      
	    	    	      
	    	    	   l=nodl.item(1).getChildNodes();
	    	    	   el=(Element) l.item(4);
	    	    	   
	    	    	   intent.putExtra("poza1",el.getAttribute("data"));
	    	    	         
	    	    	   
	    	    	   el=(Element) l.item(0);
	    	    	   intent.putExtra("condition",el.getAttribute("data"));
	    	    	   
	    	    	   el=(Element) l.item(2);
	    	    	   intent.putExtra("temp1",el.getAttribute("data"));
	    	    	   
	    	    	   el=(Element) l.item(3);
	    	    	   intent.putExtra("umid1",el.getAttribute("data"));
	    	    	   
	    	    	   
	    	    	   el=(Element) l.item(5);
	    	    	   intent.putExtra("vant1",el.getAttribute("data"));
	    	    	   
	    	    	   
	    	    	   l=nodl.item(2).getChildNodes();
	    	    	   
	    	    	   el=(Element) l.item(0);
	    	    	   intent.putExtra("maine",el.getAttribute("data"));
	    	    	   el=(Element) l.item(1);
	    	    	   intent.putExtra("low2",el.getAttribute("data"));
	    	    	   el=(Element) l.item(3);
	    	    	   intent.putExtra("poza2",el.getAttribute("data"));
	    	    	   el=(Element) l.item(4);
	    	    	   intent.putExtra("cond2",el.getAttribute("data"));
	    	    	   
	    	    	   
	    l=nodl.item(3).getChildNodes();
	    	    	   
	    	    	   el=(Element) l.item(0);
	    	    	   intent.putExtra("poimaine",el.getAttribute("data"));
	    	    	   el=(Element) l.item(1);
	    	    	   intent.putExtra("low3",el.getAttribute("data"));
	    	    	   el=(Element) l.item(3);
	    	    	   intent.putExtra("poza3",el.getAttribute("data"));
	    	    	   el=(Element) l.item(4);
	    	    	   intent.putExtra("cond3",el.getAttribute("data"));
	    	    	   
	    l=nodl.item(4).getChildNodes();
	    	    	   
	    	    	   el=(Element) l.item(0);
	    	    	   intent.putExtra("raspoimaine",el.getAttribute("data"));
	    	    	   el=(Element) l.item(1);
	    	    	   intent.putExtra("low4",el.getAttribute("data"));
	    	    	   el=(Element) l.item(3);
	    	    	   intent.putExtra("poza4",el.getAttribute("data"));
	    	    	   el=(Element) l.item(4);
	    	    	   intent.putExtra("cond4",el.getAttribute("data"));  	   
	    	    	   
	    	    	   
	    	    	   
	    	    	   
	    	    	      startActivity(intent);
	    	    
	    	    	      }
	    	    	        catch( Exception ex ) {
	    	    	        	
	    	    	        	//Toast.makeText(Prognoza.this,"Teapa", 5000).show();   nu stiu de ce nu merge:D
	    	    	        }
	    	    		
	    	    	
	        		Prognoza.this.runOnUiThread(new Runnable() {
						
						public void run() {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					});
	        	}
	    
	        }.start();
	      dialog.show();
	   
	        
	    	
	    	 	
	    
	    } 
	        
	    }








class PersonajeAdapter extends BaseAdapter
{
	private Activity context;
	ArrayList<String> orase;
 
	public PersonajeAdapter (Activity _context)
	{
		this.context = _context;
		orase = new ArrayList<String>();
	}
	
	public String ialista()
	
	{StringBuffer l = new StringBuffer ();
		for(int i=0;i<orase.size();i++)
		{l.append(orase.get(i));
		l.append ("\n");}
		
		return l.toString();
	}
	
 
	public View getView(int position, View convertView, ViewGroup list) 
	{
		
		 
		View element;
		if (convertView==null)
		{
			LayoutInflater inflater = context.getLayoutInflater();
			element = inflater.inflate(R.layout.personaj, null);
		}
		else element = convertView;
		
		
 
		TextView nume = (TextView)element.findViewById(R.id.oras);
		
 
		nume.setText(orase.get(position));
		
       
		return element;
	}
 
	public int getCount ()
        {
		
                return orase.size ();
	}
 
	public Object getItem(int position) 
	{
		
		return orase.get(position);
	}
 
	public long getItemId(int position) 
	{
		
		return 0;
	}
 
        public void adaugaOras(String nume)
        {
            
            
             
              orase.add (nume);
              Collections.sort(orase);
              
              this.notifyDataSetChanged();
        }
        
        
        public void stergeOras(int pozitie)
        {orase.remove(pozitie);
        	
        this.notifyDataSetChanged();
        }
        
        
        
        
        
        
        
}




